from django.shortcuts import render
from django.shortcuts import redirect
from django.shortcuts import reverse
from django.shortcuts import HttpResponse
from django import views
from django.db import DatabaseError
from rbac import models
from rbac.forms.menu import MenuModelForm

class MenuListView(views.View):
    '''
    菜单展示
    '''
    def get(self,request):
        menus=models.Menu.objects.all()
        mid=request.GET.get('mid')
        root_permission_list=[]
        root_permission_dict = {}
        if mid:
            #菜单下 可以成为菜单的权限
            permissions_obj=models.Permission.objects.filter(menu_id=mid)
        else:
            #可以成为菜单的权限
            permissions_obj=models.Permission.objects.filter(menu__isnull=False)
        #可以成为菜单的权限的集合
        root_permission_queryset=permissions_obj.values('id','title','url','name','menu__title')
        #子权限的权限集合
        node_permission_queryset=models.Permission.objects.filter(parent_id__in=permissions_obj).values('id','title','url','name','parent_id')

        #构建父权限字典
        for item in root_permission_queryset:
            item['children']=[]
            root_permission_list.append(item)
            root_permission_dict[item['id']]=item

        for node in node_permission_queryset:
            parent_id=node['parent_id']
            root_permission_dict[parent_id]['children'].append(node)

        return render(request,'rbac/menu_list.html',{'menu_list':menus,'mid':mid,'root_permission_list':root_permission_list})


class MenuAddView(views.View):
    '''
    菜单添加
    '''
    def get(self,request):
        menu_model_form=MenuModelForm()
        return render(request,'rbac/menu_change.html',{'form':menu_model_form})


class MenuEditView(views.View):
    '''
    菜单编辑
    '''
    def get(self,request):
        return render(request,'rbac/menu_change.html')


class MenuDeleteView(views.View):
    '''
    菜单删除
    '''
    def get(self,request):
        return render(request,'rbac/menu_change.html')